﻿# encoding:utf-8
import time
from wxpy import *

from wxpyImport import *
from db.__init__ import *
from wxpyUserService import *
from wxpyGroupUserService import *
from wxpyUpload import *

initLogger()

#os._exit(0)

# 初始化机器人，扫码登陆
bot = Bot(console_qr=1, cache_path=True)

# 启用 puid 属性，并指定 puid 所需的映射数据保存/载入路径
bot.enable_puid('wxpy_puid.pkl')

# 搜索名称含有的好友
friends = bot.friends().search('叶艺')
if len(friends)>0:
    my_friend = friends[0]

    # 发送文本给好友
    logSuccessStr = '登录成功 ' + str(my_friend.puid) + ' ' + time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))\
        + '\n' + os.getcwd() + '\n\n'
    my_friend.send(logSuccessStr)
    logInfo(logSuccessStr)
    #logInfo(obj2JsonStr(my_friend))

# 保存当前登录者
setBot(bot)

updateFriendsThread(bot, 1)

updateGroupAndUserThread(bot, 1)


# 获取并处理所有类型的消息（好友消息、群聊、公众号）
@bot.register(except_self=False)
def handleReceiveMsg(msg):
    logInfo(msg)
    logInfo(msg.create_time)
    logInfo(msg.type)
    sender = msg.sender
    if isGroup(msg.sender): # 别人发到群里的消息
        # 群名
        logInfo(msg.sender.name)
        # 发送者名
        logInfo(msg.member.name)
        sender = msg.member
    else:
        # 发送者名
        logInfo(msg.sender.name)
    # 接收者名
    if not isCurUser(msg.receiver):
        logInfo(msg.receiver.name)
    logInfo(msg.text)

    dbd = dbData()

    # 保存用户
    try:
        if isGroup(msg.sender): # 别人发到群里的消息
            # 发送者（是群）
            addGroupThread(msg.sender)
            # 发送人
            addOrUpdateUser(dbd, msg.member)
        else:
            # 发送人
            addOrUpdateUser(dbd, msg.sender)
        
        # 接收者也有可能是群（我自己发到群）
        if isGroup(msg.receiver):
            # 接收者（是群）
            addGroupThread(msg.receiver)
        else:
            # 保存接收者
            addOrUpdateUser(dbd, msg.receiver)
    except Exception as e:
        dealException()
        logError('handleReceiveMs addGroupThrea err: '+str(e))

    # 先更新群，再保存消息，因为有些群信息很旧，用户没有 puid 导致存消息失败
    try:
        dbAddMsg(dbd, msg)
    except Exception as e:
        dealException()
        logError('handleReceiveMs dbAddMs err: '+str(e))

    try:
        #判断是否需要上传该图片
        b = uploadImgIsMsgNeedUpload(dbd, msg)
        if b:
            uploadMsgImgThread(msg)
    except Exception as e:
        dealException()
        logError('handleReceiveMs uploadImgIsMsgNeedUploa err: '+str(e))

    try:
        #判断是否需要上传该头像
        b = uploadImgIsAvatarNeedUpload(dbd, sender, 1)
        if b:
            logInfo('before uploadAvatarImgThrea '+str(sender))
            uploadAvatarImgThread(sender)
    except Exception as e:
        dealException()
        logError('handleReceiveMs uploadImgIsAvatarNeedUploa err: '+str(e))
    
    closeDb(dbd)


# 进入 Python 命令行、让程序保持运行
embed()